# 发送邮件（提醒是否购票成功）
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

import yaml  # 格式化邮件地址的显示形式

sender = "2259547703@qq.com"  
pwd = "bkjvmjzjynkjeaea"
receiver = ''

with open('config.yml', 'r', encoding='utf-8') as f:
    config = yaml.safe_load(f)

def mail(message):
    receiver_list = getMails()
    if receiver_list is None or len(receiver_list) == 0:
        return False
    ret = True
    try:
        # current_dt = time.strftime('%Y-%m-%d', time.localtime())
        msg = MIMEText(message, 'plain', 'utf-8')
        # 最终邮件头效果: From: ^_^ <user@qq.com>
        msg['From'] = formataddr(["收文小助手", sender])  # 发件人昵称
        msg['To'] = formataddr(["^v^", receiver])  # 收件人昵称
        msg['Subject'] = "新的来文待处理"

        server = smtplib.SMTP_SSL('smtp.qq.com', 465)
        server.login(sender, pwd)
        server.sendmail(sender, receiver_list, msg.as_string())
        server.quit()
    except Exception as e:
        ret = False
        print(e)
    return ret

def getMails():
    # 从本地mails.txt读取接收人邮箱
    with open(config['code_dir'] + '/mails.txt', 'r', encoding='utf-8') as f:
        receiver_txt = f.read().strip()
    # 将字符串转为列表
    receiver_list = receiver_txt.split(',')
    return receiver_list